package com.gosophia.conference.action.notification;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;

import com.gosophia.commons.web.action.BaseSupportAction;
import com.gosophia.commons.web.logAnnotation.LogRecord;
import com.gosophia.conferenceManagement.ConferenceTurningAction;
import com.gosophia.conferenceManagement.common.entity.DocumentInfo;
import com.gosophia.conferenceManagement.common.service.ConferenceFileService;
import com.gosophia.conferenceManagement.notification.dto.SendNotificationJobDataDTO;
import com.gosophia.conferenceManagement.notification.ws.SendNotificationWebService;
import com.gosophia.oa.action.JudgeCurrentUndertaker;
import com.gosophia.springsecurity.UserDetailsImpl;
import com.gosophia.taskManagement.dto.JobDTO;
import com.gosophia.taskManagement.ws.TaskManagementWebService;
import com.gosophia.userManagement.dto.UserAccountDTO;
import com.gosophia.userManagement.dto.UserInfoDTO;
import com.gosophia.userManagement.ws.UserManagementWebService;
import com.gosophiaigit.contact.busi.entity.Contact;
import com.gosophiaigit.contact.busi.service.IContactGroupService;
import com.opensymphony.xwork2.ActionContext;
/**
 *  发送通知Action
 * @author gaoweiguang
 * @since  2011-3-26
 *  Copyright (c) 2010 Gosophia corporation All Rights Reserved
 */
@Scope("prototype")
@Controller("SendNotificationMailAction")
public class SendNotificationMailAction extends BaseSupportAction{

	private static final long serialVersionUID = 6977464522284737661L;

	@Autowired
	private UserManagementWebService userManagementWebService;

	@Autowired
	private ConferenceFileService conferenceFileService; 
	
	@Autowired
	private SendNotificationWebService sendNotificationWebService;
	
    @Autowired
    private TaskManagementWebService taskManagementWebService;

	@Autowired
	private JudgeCurrentUndertaker judgeCurrentUndertaker;

	@Autowired
	private IContactGroupService iContactGroupService; 

    private String onlineIsEdit = "0,0";
    
	private String onlinePath;
	
	private String onlineVersion;
	
    private Long jobId;
    
    private SendNotificationJobDataDTO sendNotificationJobDataDTO;

	private String notificationType;
	@Override
	@LogRecord(eventAction = "会议置办-发送会议通知", eventTarget = "sendNotificationJobDataDTO")
	public String _execute() throws Exception {
		 //判断是否匹配,如果不匹配转到异常页面
        judgeCurrentUndertaker.judgeOperationAuthority(jobId);
		UserDetailsImpl userDetails = (UserDetailsImpl) SecurityContextHolder
	      .getContext().getAuthentication().getPrincipal();

		String title = "会议通知";//所发送邮件的标题
		
		JobDTO missJob = taskManagementWebService.findJobDetailByJobId(jobId);

		List<UserInfoDTO> sendTo = new ArrayList<UserInfoDTO>();
		for(Long receiveId:sendNotificationJobDataDTO.getReceiveUserId()) {
			List<UserInfoDTO> userInfoDtos = userManagementWebService.findAllUserInfo();
            for(UserInfoDTO usrs:userInfoDtos) {
                if(receiveId.equals(usrs.getUserInfoId())) {
                	sendTo.add(usrs);
                }
            }
		}
		DocumentInfo docInfo = null;
        if(onlinePath!=null && !"notificationJobDataDTO.onlineDocumentDTO.documentPath".equals(onlinePath)) {
        	//获取文档
    		docInfo =conferenceFileService.loadDocumentByPath(onlinePath);
        }
		
		List<String> filenames = new ArrayList<String>();
		File f1=new File("c:/文档附件.doc");
		if(docInfo!=null) {
			InputStream fileIo = docInfo.getDocumentContent();
	        FileOutputStream o=new FileOutputStream(f1);  
	        byte b[]=new byte[4000];
	        int n;
	        while((n=fileIo.read(b))!=-1)  
	        {o.write(b,0,n);  
	        }
	        o.close(); 
	        fileIo.close();
	        
	        String path = "c:/文档附件.doc";
	       
	        filenames.add(path);

		}
        
		Boolean sendFlg = false;
		HttpServletRequest request = ServletActionContext.getRequest();
//	    int serverPort=request.getServerPort();
	    String ip = request.getHeader("Host");
		if(sendTo!=null&&sendTo.size()!=0) {
			for(UserInfoDTO receiveUser:sendTo) {
				List<String> receiveMail = new ArrayList<String>();
				String content = null;
				if("1".equals(notificationType)) {
					UserAccountDTO userAccountDTO = userManagementWebService.findUserAccountByUserInfoId(receiveUser.getUserInfoId());
					if(userAccountDTO!=null) {
					   //邮件的文本内容，可以包含html标记则显示为html页面 
					   content = "</br><a href='http://"+ip+"/OA/web/getNotificationFeedBackAction.action?jobId=" + jobId + "&userId="+receiveUser.getUserInfoId()+"'>请您点击，确定是否参加会议</a>";
					}else {
					   //邮件的文本内容，可以包含html标记则显示为html页面 
					   content = "</br><a href='http://"+ip+"/OA/web/getNotificationFeedBackWithNoUserCountAction.action?jobId=" + jobId + "&userId="+receiveUser.getUserInfoId()+"'>请您点击，确定是否参加会议</a>";
					}
					
					
				}else {
					content = "</br>通知您参加"+missJob.getMissionDTO().getMissionName() +"</br>";
				}
				List<Contact> sendContacts = iContactGroupService.findAllContactList();
				for(Contact contact:sendContacts) {
					if(receiveUser.getUserInfoId().equals(contact.getUserInfoId())) {
						receiveMail.add(contact.getEmail());
						break;
					}
				}
				if(sendmail(title,receiveMail,content,filenames,"text/html;charset=gbk"))
					 sendFlg = true;
			}
		}
		
		
	    if(sendFlg){
			Long userInfoId = userDetails.getUserAccountDTO().getUserInfoDTO().getUserInfoId();
			sendNotificationJobDataDTO.setSendNotificationType(notificationType);
			sendNotificationJobDataDTO.setTurningAction(ConferenceTurningAction.DEFAULT_ACTION.getValue());
			sendNotificationJobDataDTO.setJobId(jobId);
			sendNotificationJobDataDTO.setOperatorId(userInfoId);
			sendNotificationWebService.sendMail(sendNotificationJobDataDTO);
			if(f1!=null) {
				if(f1.exists()){
		       		f1.delete();
		       	}	
			}
	       	
	       	
			super.getRequestResult().setRsltCode("0");
			if("0".equals(notificationType)) {
			   super.getRequestResult().setMessage("会议预通知发送成功");
		    } else if("1".equals(notificationType)) {
			  super.getRequestResult().setMessage("会议正式通知发送成功");
		     }
			ActionContext.getContext().getSession().put("_lastOpResult", super.getRequestResult());
			if("task".equals(this.getFromFlag())){
				return "TASK";
			}
	    }
		return SUCCESS;
	}

	
	public static boolean sendmail(String subject, List<String> to, String text, List<String> filenames,String mimeType) throws Exception 
	{ 
	//ResourceBundle mailProps = ResourceBundle.getBundle("mail"); 可以从配置文件读取相应的参数 
	Properties props = new Properties();
	 //得到spring的context对象
    ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:conference-sendMail.xml");
	String smtp = null;
	JavaMailSenderImpl  javaMailSenderImpl = (JavaMailSenderImpl)ctx.getBean("mailSender");
	smtp = javaMailSenderImpl.getHost();

	String servername = javaMailSenderImpl.getUsername(); 
	String serverpaswd = javaMailSenderImpl.getPassword();

	javax.mail.Session mailSession; //邮件会话对象 
	javax.mail.internet.MimeMessage mimeMsg; //MIME邮件对象 

	props = java.lang.System.getProperties(); //获得系统属性对象 
	props.put("mail.smtp.host", smtp); //设置SMTP主机 
	props.put("mail.smtp.auth", "true"); //是否到服务器用户名和密码验证 
	String from = javaMailSenderImpl.getUsername(); 
	MyAuthenticator myEmailAuther = new MyAuthenticator(servername, serverpaswd);

    	//设置邮件会话 
    	mailSession = javax.mail.Session.getInstance(props, (Authenticator) myEmailAuther);  
    	//设置传输协议 
    	Transport transport = mailSession.getTransport("smtp");
    	//设置from、to等信息 
    	mimeMsg = new javax.mail.internet.MimeMessage(mailSession); 
    	if (!StringUtils.isEmpty(from)) 
    	{ 
    	InternetAddress sentFrom = new InternetAddress(from); 
    	mimeMsg.setFrom(sentFrom); //设置发送人地址 
    	} 

    	InternetAddress[] sendTo = new InternetAddress[to.size()]; 
    	for (int i = 0; i < to.size(); i++) 
    	{
    	sendTo[i] = new InternetAddress(to.get(i)); 
    	} 

    	mimeMsg.setRecipients(javax.mail.internet.MimeMessage.RecipientType.TO, sendTo); 
    	mimeMsg.setSubject(subject, "gbk"); 
    	//MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象   
    	Multipart mainPart = new MimeMultipart();   
    	//创建一个包含HTML内容的MimeBodyPart   
    	BodyPart html = new MimeBodyPart();   
    	//设置HTML内容   
    	html.setContent(text,"text/html; charset=gbk");   
    	mainPart.addBodyPart(html);   
    	// 将MiniMultipart对象设置为邮件内容   
    	mimeMsg.setContent(mainPart);
    	if(filenames!=null && filenames.size()!=0) {
    		for(String f:filenames){   
        		html=new MimeBodyPart();
        		FileDataSource fds=new FileDataSource(f);
        	    html.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart
        	    String displayfilename = MimeUtility.encodeWord("会议公文附件.doc","utf-8", null);
        	    html.setFileName(displayfilename);  //得到文件名同样至入BodyPart      
        	    mainPart.addBodyPart(html);      
        	}	
    	}
    	   
    	// 将MiniMultipart对象设置为邮件内容   
    	mimeMsg.setContent(mainPart);
    	//设置信件头的发送日期 
    	mimeMsg.setSentDate(new Date()); 
    	mimeMsg.saveChanges(); 
    	//发送邮件 
    	Transport.send(mimeMsg); 
    	transport.close();
    	return true; 
 
	} 
	
	
	
	public Long getJobId() {
		return jobId;
	}

	public void setJobId(Long jobId) {
		this.jobId = jobId;
	}

	public String getOnlineIsEdit() {
		return onlineIsEdit;
	}


	public void setOnlineIsEdit(String onlineIsEdit) {
		this.onlineIsEdit = onlineIsEdit;
	}


	public String getOnlinePath() {
		return onlinePath;
	}


	public void setOnlinePath(String onlinePath) {
		this.onlinePath = onlinePath;
	}


	public String getOnlineVersion() {
		return onlineVersion;
	}


	public void setOnlineVersion(String onlineVersion) {
		this.onlineVersion = onlineVersion;
	}


	public SendNotificationJobDataDTO getSendNotificationJobDataDTO() {
		return sendNotificationJobDataDTO;
	}


	public void setSendNotificationJobDataDTO(
			SendNotificationJobDataDTO sendNotificationJobDataDTO) {
		this.sendNotificationJobDataDTO = sendNotificationJobDataDTO;
	}


	public String getNotificationType() {
		return notificationType;
	}


	public void setNotificationType(String notificationType) {
		this.notificationType = notificationType;
	}

	
}
